import { guid, timeFormat, timeFrom } from 'uview-plus';
// 格式化日期 当天显示小时分钟，七天内显示几天前，超过7天显示年月日
export const DateFormat = (time: string) => {
  const now = new Date();
  const targetDate = new Date(Date.parse(time));

  // 检查是否是同一天
  const isSameDay = now.getFullYear() === targetDate.getFullYear() &&
    now.getMonth() === targetDate.getMonth() &&
    now.getDate() === targetDate.getDate();

  if (isSameDay) {
    return timeFormat(targetDate, 'hh:MM');
  } else {
    const diffTime = Math.abs(now.getTime() - targetDate.getTime());
    const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));

    if (diffDays <= 7) {
      return timeFormat(targetDate, 'mm/dd hh:MM');
    } else {
      return timeFormat(targetDate, 'yy/mm/dd');
    }
  }
};

export const formatSeconds=(seconds: number): string=> {
  const roundedSeconds = Math.round(seconds);
  const hours = Math.floor(roundedSeconds / 3600);
  const minutes = Math.floor((roundedSeconds % 3600) / 60);
  const remainingSeconds = roundedSeconds % 60;

  let result = '';
  if (hours > 0) {
    result += `${hours.toString().padStart(2, '0')}:`;
  }
  result += `${minutes.toString().padStart(2, '0')}:`;
  result += `${remainingSeconds.toString().padStart(2, '0')}`;

  return result;
}


export const captureCover =async (videoPath: string): Promise<string> => {

  // #ifdef MP-WEIXIN || APP-PLUS
  const videoInfo = await uni.getVideoInfo({ src: videoPath });
  const canvasContext = uni.createCanvasContext('videoCoverCanvas');
  canvasContext.drawImage(videoPath, 0, 0, videoInfo.width, videoInfo.height);
  canvasContext.draw();
  const { tempFilePath } = await uni.canvasToTempFilePath({
    canvasId: 'videoCoverCanvas',
    width: videoInfo.width,
    height: videoInfo.height
  });
  return tempFilePath;
  // #endif

  // #ifdef H5
  return await getVideoCoverH5(videoPath)
  // #endif
};

export const getVideoCoverH5 = async (videoPath: string): Promise<{
  base64: string;
  file: File;
}> => {
  // #ifdef H5
  return new Promise((resolve, reject) => {
    const video = document.createElement('video');
    const canvas = document.createElement('canvas');
    let timer: ReturnType<typeof setTimeout>;
    let blobUrl: string | null = null;

    const initVideo = () => {
      video.muted = true;
      video.playsInline = true;
      video.crossOrigin = 'anonymous';
      video.preload = 'auto';

      const tryCapture = async () => {
        const ctx = canvas.getContext('2d');
        if (!ctx) return;

        try {
          ctx.drawImage(video, 0, 0, canvas.width, canvas.height);

          // 验证是否黑屏
          const pixel = ctx.getImageData(0, 0, 1, 1).data;
          if (pixel[3] === 0) throw new Error('黑屏');

          // 同时生成base64和File
          const base64 = canvas.toDataURL('image/jpeg');
          const file = await new Promise<File>((res) => {
            canvas.toBlob((blob) => {
              res(new File(
                [blob!],
                `cover_${Date.now()}.jpg`,
                { type: 'image/jpeg' }
              ));
            }, 'image/jpeg', 0.8);
          });

          clearTimeout(timer);
          resolve({ base64, file });
        } catch (error) {
          console.warn('捕获失败:', error);
        }
      };

      video.addEventListener('loadedmetadata', () => {
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        video.currentTime = 0.001;

        ['seeked', 'canplay'].forEach(evt => {
          video.addEventListener(evt, tryCapture, { once: true });
        });

        video.play().catch(tryCapture);

        timer = setTimeout(() => {
          tryCapture();
          reject(new Error('封面生成超时'));
        }, 3000);
      });

      video.addEventListener('error', (err) => {
        clearTimeout(timer);
        reject(new Error(`视频加载失败: ${err.target?.error}`));
      });
    };

    if (videoPath.startsWith('blob:')) {
      video.src = videoPath;
      initVideo();
    } else {
      fetch(videoPath)
        .then(res => res.blob())
        .then(blob => {
          blobUrl = URL.createObjectURL(blob);
          video.src = blobUrl;
          initVideo();
        })
        .catch(reject);
    }
  });
  // #endif
};

